<template>
  <div class="flex justify-between text-[#000] text-xl pb-10">
    <div
      class="flex items-center cursor-pointer"
      @click="emits('handleReturn')"
    >
      <el-icon>
        <ArrowLeftBold />
      </el-icon>
      <p class="pl-2">{{ $t("忘记密码") }}</p>
    </div>
  </div>
  <div>
    <el-tabs class="custom-tabs" v-model="activeName" @tab-change="handelClick">
      <el-tab-pane :label="$t('邮箱')" name="email"></el-tab-pane>
      <el-tab-pane :label="$t('手机号码')" name="mobile"></el-tab-pane>
    </el-tabs>
    <el-form ref="formRef" :model="form" status-icon :rules="rules">
      <el-form-item prop="email" v-if="activeName == 'email'">
        <el-input
          v-model="form.email"
          size="large"
          :placeholder="$t('请输入账号')"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="mobile" v-else>
        <el-input
          v-model="form.mobile"
          :placeholder="$t('请输入手机号码')"
          size="large"
          @input="handleInput"
        >
          <template #prepend>
            <el-select
              v-model="form.mobile_area_code"
              :placeholder="$t('区号')"
              size="large"
              style="width: 100px"
              popper-class="custom-selectDropDown"
            >
              <el-option
                v-for="item in options"
                :key="item.area_code"
                :label="item.label"
                :value="item.area_code"
              >
                <span>{{ item.country }}</span>
                <span>{{ item.area_code }}</span>
              </el-option>
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="flex items-center justify-between flex-1 mt-2">
          <el-input
            v-model="form.code"
            :placeholder="$t('请输入验证码')"
            size="large"
          >
          </el-input>

          <el-button
            size="large"
            type="primary"
            class="ml-4"
            @click="handleCaptcha"
            :disabled="form.email === '' && form.mobile == ''"
            v-if="!codesms.disabled"
          >
            {{ $t("获取验证码") }}
          </el-button>
          <el-button size="large" type="primary" class="ml-4" disabled v-else>
            {{ codesms.count }}{{ $t("秒后重新获取") }}
          </el-button>
        </div>
      </el-form-item>
      <div
        class="flex flex-col justify-start items-start text-xs text-[#AAAAAA]"
      >
        <span>{{ $t("若收不到验证码，请联系客服") }}</span>
        <span>{{ $t("客服What‘s App:", { code: "12133974557" }) }}</span>
      </div>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="form.password"
          show-password
          size="large"
          class="mt-2"
          :placeholder="$t('请设置新密码')"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="again_password">
        <el-input
          type="password"
          v-model="form.again_password"
          show-password
          size="large"
          class="mt-2"
          :placeholder="$t('请再次输入新密码')"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <el-button
      size="large"
      type="primary"
      class="w-full mt-2"
      :loading="loading"
      @click="onSubmit"
    >
      {{ $t("提交") }}
    </el-button>
  </div>
</template>
<script setup>
const emits = defineEmits(["handleReturn"]);
import { reactive, ref, computed, nextTick } from "vue";

import {
  resetNewPasswordApi,
  emailSendApi,
  getCountryArea,
} from "@/api/login/index";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const loading = ref(false);
const formRef = ref();
const activeName = ref("email");
const codesms = reactive({
  disabled: false,
  total: 60,
  count: 0,
});
const handleInput = (value) => {
  if (value.length > 16) {
    form.mobile = value.slice(0, 16);
  } else {
    form.mobile = value;
  }
};
const options = ref([]);
const getAreaList = async () => {
  const res = await getCountryArea();
  options.value = res || [];
  form.mobile_area_code = res[0].area_code || "";
};
getAreaList();

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入新密码"));
  } else if (value !== form.password) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};
// 校验
const rules = computed(() => {
  return {
    email: [{ required: true, message: t("请输入账号"), trigger: "blur" }],
    mobile: [
      { required: true, message: t("请输入账号"), trigger: "blur" },
      { min: 6, max: 16, message: t("请输入6-16位的数字"), trigger: "change" },
    ],
    password: [{ required: true, message: t("请输入新密码"), trigger: "blur" }],
    code: [{ required: true, message: t("请输入验证码"), trigger: "blur" }],
    again_password: [
      { required: true, validator: validatePass2, trigger: "blur" },
    ],
  };
});

const form = reactive({
  email: "",
  mobile: "",
  mobile_area_code: "",
  password: "",
  again_password: "",
  code: "",
});
// 倒计时
const timerHandle = () => {
  codesms.count = codesms.total;
  codesms.disabled = true;

  let timer = setInterval(() => {
    if (codesms.count > 1 && codesms.count <= codesms.total) {
      codesms.count--;
    } else {
      codesms.disabled = false;
      clearInterval(timer);
    }
  }, 1000);
};

//发送验证码
const handleCaptcha = async () => {
  try {
    timerHandle();
    if (activeName == "email") {
      const res = await emailSendApi({
        email: form.email,
        code_type: "forgot_password",
      });
    }
    ElMessage({
      type: "success",
      message: "发送验证码成功",
    });
  } catch (error) {}
};

const handelClick = () => {
  nextTick(() => {
    formRef.value.resetFields();
    form.mobile = "";
    form.email = "";
  });
};

//提交
const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      try {
        loading.value = true;
        // 1.调用忘记密码接口
        // console.log(form);
        const res = await resetNewPasswordApi(form);
        ElMessage({
          message: "修改密码成功",
          type: "success",
        });
        emits("handleReturn");
      } catch (error) {
        loading.value = false;
      }
    })
    .catch((error) => {
      // console.log(error);
    });
};
</script>
